package com.app.view;

import android.content.Context;
import android.graphics.Canvas;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.TextView;

/**
 *  分散对齐Label简单实现,只支持单行文本
 */
public class DistributedLabel extends TextView {
    private int measureWidth;

    public DistributedLabel(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        String text = null;
        if(getText() instanceof String) {
            text = (String) getText();
        }

        if(!TextUtils.isEmpty(text) && text.length() > 1) {
            TextPaint paint = getPaint();
            paint.setColor(getCurrentTextColor());
            paint.setTextSize(getTextSize());
            paint.drawableState = getDrawableState();

            measureWidth = getMeasuredWidth();

            // 这里只考虑单行文本
            Layout layout = getLayout();
            int lineStart = layout.getLineStart(0);
            int lineEnd = layout.getLineEnd(0);

            String line = text.substring(lineStart, lineEnd);

            float width = StaticLayout.getDesiredWidth(line, lineStart, lineEnd, getPaint());
            float gap = (getMeasuredWidth() - width) / (text.length() - 1);
            float wordWidth = width / text.length();

            int paddingLeft = getPaddingLeft();
            int paddingRight = getPaddingRight();

            float lineY = getTextSize();

            for(int i=0;i<text.length();i++) {
                if(i == text.length() - 1) {
                    canvas.drawText(text.charAt(i) + "",getMeasuredWidth() - paddingRight - wordWidth,lineY,paint);
                } else {
                    canvas.drawText(text.charAt(i) + "", paddingLeft + (gap + wordWidth) * i, lineY, paint);
                }
            }

        } else {
            super.onDraw(canvas);
        }
    }
}
